package com.xn.app.muying.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JsResult;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.xn.app.muying.R;
import com.xn.app.muying.util.APIMethod;
import com.xn.app.muying.util.BaseActivity;
import com.xn.app.muying.util.MyAlertDialog;
import com.xn.app.muying.util.NetworkUtil;
import com.xn.app.muying.util.ToastUtil;

import org.w3c.dom.Text;

import java.net.URL;
import java.util.HashMap;

/**
 * 显示web页面
 * Created by Administrato on 2017/8/6.
 */

public class WebActivity extends BaseActivity {

    //标题
    private TextView title = null;
    //返回键
    private ImageView img_back = null;
    //接收页面传来的数据
    private Intent intent = null;
    //保存标题
    private String titleStr = null;
    //保存需要加载的URL
    private String urlStr = null;
    //显示
    private WebView webView = null;
    //加载框
    MyAlertDialog mDialog;
    //判断页面是否加载完成
    private boolean lean = false;

    public final static int FILECHOOSER_RESULTCODE = 1;
    public final static int FILECHOOSER_RESULTCODE_FOR_ANDROID_5 = 2;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.web_activity);
        //初始化组件
        init();
    }

    @SuppressLint("AddJavascriptInterface")
    private void init() {
        title = (TextView) findViewById(R.id.title_name);
        img_back = (ImageView) findViewById(R.id.img_back);
        webView = (WebView) findViewById(R.id.webview);
        //接收传来的数据
        intent = getIntent();
        titleStr = intent.getStringExtra("title");
        urlStr = intent.getStringExtra("url");
        //设置标题
        title.setText(titleStr);
        //设置返回键点击事件
        img_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (webView.canGoBack()) {
                    webView.goBack();// 返回前一个页面
                } else {
                    webView.onResume();
                    finish();
                }
            }
        });

        //显示数据
        if (NetworkUtil.isNetworkAvailable(this)) {
            webView.setVisibility(WebView.VISIBLE);
            WebSettings mWebSettings = webView.getSettings();
            mWebSettings.setJavaScriptEnabled(true);
            mWebSettings.setDomStorageEnabled(true);
//            mWebSettings.setLoadWithOverviewMode(true);
//            mWebSettings.setUseWideViewPort(true);
//            mWebSettings.setDefaultTextEncodingName("GBK");
//            mWebSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
//            mWebSettings.setSavePassword(true);
//            mWebSettings.setSaveFormData(true);

            // 设置可以访问文件
//            mWebSettings.setAllowFileAccess(true);
//            webView.setScrollBarStyle(0);
            webView.requestFocus();
            webView.loadUrl(urlStr);
        } else {
            ToastUtil.showToast(this, R.string.no_network_hint);
        }

        //数据监听
        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                // TODO 自动生成的方法存根
                if (newProgress == 100) {
                } else {
                }

            }


            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                //如果是其他页面，则更改为相应标题
            }

//            @Override
//            public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
//                AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
//                builder.setTitle("xxx提示").setMessage(message).setPositiveButton("确定", null);
//                builder.setCancelable(false);
//                builder.setIcon(R.mipmap.ic_launcher);
//                AlertDialog dialog = builder.create();
//                dialog.show();
//                result.confirm();
//                return true;
//            }

            //扩展浏览器上传文件
            //3.0++版本
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
                openFileChooserImpl(uploadMsg);
            }

            //3.0--版本
            public void openFileChooser(ValueCallback<Uri> uploadMsg) {
                openFileChooserImpl(uploadMsg);
            }

            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
                openFileChooserImpl(uploadMsg);
            }

            @Override
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
                onenFileChooseImpleForAndroid(filePathCallback);
                return true;
            }
        });
        //web监听
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                // TODO Auto-generated method stub
                if (url.contains("alipays://platformapi")) {
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    startActivity(intent);
                    return false;
                } else if (url.contains("weidianbuyer")) {
                    return false;
                } else {
                    HashMap<String, String> map = new HashMap<String, String>();
                    map.put("Referer", view.getUrl());
                    view.loadUrl(url, map);
                    //返回值是true的时候控制去WebView打开，为false调用系统浏览器或第三方浏览器
                    return false;
                }

            }

            //页面开始加载
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                if (!lean) {
                    mDialog = new MyAlertDialog();
                    mDialog.ShowDialogWeb(WebActivity.this, R.layout.dialog_loading);
                    lean = true;
                }
            }

            //加载结束 （其实页面404等等错误的情况也算加载完成）
            @Override
            public void onPageFinished(WebView view, String url) {
                if (lean && mDialog != null) {
                    mDialog.dismissAd();
                    lean = false;
                }
                view.requestFocusFromTouch();
                super.onPageFinished(view, url);
            }
        });

//        // 解决输入框不能输入的bug
//        webView.setOnTouchListener(new View.OnTouchListener() {
//            @Override
//            public boolean onTouch(View v, MotionEvent event) {
//
//                switch (event.getAction()) {
//                    case MotionEvent.ACTION_DOWN:
//                    case MotionEvent.ACTION_UP:
//                        v.requestFocusFromTouch();
//                        break;
//                    case MotionEvent.ACTION_MOVE:
//                        break;
//                    case MotionEvent.ACTION_CANCEL:
//                        break;
//                }
//                return false;
//            }
//        });
    }

    public ValueCallback<Uri> mUploadMessage;
    private void openFileChooserImpl(ValueCallback<Uri> uploadMsg) {
        mUploadMessage = uploadMsg;
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.setType("image/*");
        startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);
    }

    public ValueCallback<Uri[]> mUploadMessageForAndroid5;
    private void onenFileChooseImpleForAndroid(ValueCallback<Uri[]> filePathCallback) {
        mUploadMessageForAndroid5 = filePathCallback;
        Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
        contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
        contentSelectionIntent.setType("image/*");

        Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
        chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
        chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");

        startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE_FOR_ANDROID_5);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode,Intent intent) {
        if (requestCode == FILECHOOSER_RESULTCODE) {
            if (null == mUploadMessage)
                return;
            Uri result = intent == null || resultCode != RESULT_OK ? null: intent.getData();
            mUploadMessage.onReceiveValue(result);
            mUploadMessage = null;

        } else if (requestCode == FILECHOOSER_RESULTCODE_FOR_ANDROID_5){
            if (null == mUploadMessageForAndroid5)
                return;
            Uri result = (intent == null || resultCode != RESULT_OK) ? null: intent.getData();
            if (result != null) {
                mUploadMessageForAndroid5.onReceiveValue(new Uri[]{result});
            } else {
                mUploadMessageForAndroid5.onReceiveValue(new Uri[]{});
            }
            mUploadMessageForAndroid5 = null;
        }
    }

    @Override
    protected void onDestroy() {
        try {
            ViewGroup view = (ViewGroup) getWindow().getDecorView();
            view.removeAllViews();
        } catch (Exception e) {
            e.printStackTrace();
        }
        super.onDestroy();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // 是否触发按键为back键
        if (keyCode == KeyEvent.KEYCODE_BACK&&webView.canGoBack()) {
                webView.goBack();// 返回前一个页面
            return true;
        }else{
            return super.onKeyDown(keyCode, event);
        }
    }

}
